require 'net/http'
require 'cgi'
require 'sha1'
require 'yaml'
require 'time'
require 'rubygems'
gem "actionpack"
require 'action_controller'

Mime::Type.register "image/png", :png
Mime::Type.register "image/jpeg", :jpg
Mime::Type.register "image/jpeg", :jpeg
Mime::Type.register "image/gif", :gif
Mime::Type.register "application/pdf", :pdf
# Mime::Type.register "application/xhtml+xml", :xhtml

module Mime
  class Type
    class << self
      def lookup_by_extension(ext)
        EXTENSION_LOOKUP[ext]
      end
    end
  end
end

def text_to_multipart(key,value)
  return "Content-Disposition: form-data; name=\"#{CGI::escape(key)}\"\r\n" + 
         "\r\n" + 
         "#{value}\r\n"
end

def file_to_multipart(key,filename,mime_type,content)
  return "Content-Disposition: form-data; name=\"#{CGI::escape(key)}\"; filename=\"#{filename}\"\r\n" +
         "Content-Transfer-Encoding: binary\r\n" +
         "Content-Type: #{mime_type}\r\n" + 
         "\r\n" + 
         "#{content}\r\n"
end

def extension(file_path)
  (File.extname(file_path).downcase)[1..-1].to_s
end

SPRINGNOTE_PORT = 80
SPRINGNOTE_DOMAIN = 'api.springnote.com'

CONFIG = YAML::load_file('config.yml')
open_id = CONFIG['open_id']
user_key = CONFIG['user_key']
app_id = CONFIG['app_id'] 
app_key = CONFIG['app_key']

page_id = ARGV[0]
file_path = ARGV[1]
mime_type = ARGV[2] 
mime_type = Mime::Type.lookup_by_extension(extension(file_path)) unless mime_type
mime_type = 'application/octet-stream' unless mime_type.to_s.include?('/')
puts mime_type.to_s
data = nil
File.open(file_path, 'rb') do |file|
  data = file.read
end
params = [ 
  file_to_multipart('Filedata', File.basename(file_path), mime_type.to_s, data)]

boundary = '349832898984244898448024464570528145'
query = 
  params.collect {|p| '--' + boundary + "\r\n" + p}.join('') + "--" + boundary + "--\r\n"

nonce = sprintf("%016x", rand(16 ** 16))
created = Time.now.utc.xmlschema #'2007-02-14T20:00:00Z' 
digested_key = SHA1.sha1(nonce + created + user_key + app_key).to_s
username = CGI.escape(open_id)
password = CGI.escape(app_id.to_s + ',' + nonce + ',' + created + ',' + digested_key)

Net::HTTP.start(SPRINGNOTE_DOMAIN, SPRINGNOTE_PORT) do |http|
  req = Net::HTTP::Post.new("/pages/#{page_id}/attachments.xml", 'Content-type' => "multipart/form-data; boundary=#{boundary}")
  req.basic_auth username, password
  response = http.request(req, query)
  puts response.code        
  puts response.body
end